//
//  OAuthViewController.swift
//  sinaWeiBo
//
//  Created by weixq on 15/8/1.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit
import SVProgressHUD
 
class OAuthViewController: UIViewController , UIWebViewDelegate{

    // MARK: - 搭建界面
    private lazy var webView = UIWebView()

    override func loadView() {
        view = webView
        webView.delegate = self
        
        title  = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // 关闭界面
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.authUrl()))
    }
    
    // MARK: - UIWebViewDelegate
    
    func webViewDidStartLoad(webView: UIWebView) {

        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {

        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
     
        let urlSting = request.URL!.absoluteString

        // 判断是否包含回调地址
        if !urlSting.hasPrefix(NetworkTools.sharedTools.redirectUrl){
             return true
        }
      
        if let query = request.URL?.query where query.hasPrefix("code="){
        
        // 从query重获取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
        
            loadAccessToken(code)
        
        }else{
            close()
        }
        
        return false
//        return true
    }
    
    private func loadAccessToken(code:String) {
        
   
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result ==  nil{
                self.netError()
                return
            }
            
            // 字典转模型
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                
                if error != nil {
                    self.netError()
                    return
                }
                
            // 发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(HMRootViewControllerSwitchNotification, object: false)
                
            self.close()
            })
        }
    }
    
    private func netError() {
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC*1))
        dispatch_after(when, dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    }

   }


